﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
//using System.Web.Caching;
using UdpReceive;

namespace DataServer
{
    public partial class FrmMain : Form
    {
        
        private bool _isPrintInfo = true;//是否输入调试信息
        private UdpReceiveData udpReceiveData;
        //private DataTable userTable;//存储用户DataTable
       // private DataTable clientTable;//存储客户端DataTable
        public FrmMain()
        {
            InitializeComponent();
        }
        //结束监听
        private void btn_end_Click(object sender, EventArgs e)
        {
            if (udpReceiveData != null) {
                udpReceiveData.Dispose();
            }
            AppendLog("结束监听成功!",false);
            btn_start.Enabled = true;
        }
        //窗体关闭
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (udpReceiveData != null)
            {
                udpReceiveData.Dispose();
            }
            System.Environment.Exit(System.Environment.ExitCode);
        }        

        private void chb_printinfo_CheckedChanged(object sender, EventArgs e)
        {
            _isPrintInfo = ((CheckBox)sender).Checked;
        }

        private void btn_crc_Click(object sender, EventArgs e)
        {
            string crcSourceStr = txt_crcstr.Text;
            string crcHexStr =UdpReceive.DataUtility.HexEncode(crcSourceStr);
            txt_crchex.Text = crcHexStr;
            //计算CRC
            byte[] hexByte = DataUtility.HexString2Bytes(crcHexStr);
            byte[] crcByte = CRCUtility.CalculateCRC(ref hexByte, hexByte.Length);
            string crcStr = DataUtility.ByteArrayToHexString(crcByte, crcByte.Length);
            txt_crcresut.Text = crcStr;
        }

        private void btn_hex_Click(object sender, EventArgs e)
        {
            string crcHexStr = txt_crchex.Text;
            byte[] hexByte = DataUtility.HexString2Bytes(crcHexStr);
            byte[] crcByte = CRCUtility.CalculateCRC(ref hexByte, hexByte.Length);
            string crcStr = DataUtility.ByteArrayToHexString(crcByte, crcByte.Length);
            txt_crchexre.Text = crcStr;
        }

        private void btn_start_Click(object sender, EventArgs e)
        {
            int acceptPort = 0;
            if (txt_accept_port.Text.Trim().Equals(""))
            {
                MessageBox.Show("请输入监听端口！", "提示");
                return;
            }
            int.TryParse(txt_accept_port.Text.Trim(),out acceptPort);
            if (acceptPort > 1024)
            {
                udpReceiveData = new UdpReceiveData(acceptPort);
                //udpReceiveFile.FileReceiveBuffer +=new FileReceiveBufferEventHandler(FileReceiveBuffer);
                udpReceiveData.UpdateListViewData += new UpdateListViewDataEventHandler(UpdateListViewData);
                udpReceiveData.PrintReceiveData += new PrintReceiveDataEventHandler(PrintReceiveBuffer);

                udpReceiveData.Start();
                AppendLog(string.Format("开始侦听，端口：{0}", udpReceiveData.Port), false);

                btn_start.Enabled = false;

            }
        }
        //更新界面ListView(用户、终端)信息
        private void UpdateListViewData(object sender, ListViewDataViewEventArgs e)
        {
            string lstkey=e.LstKey;
            if (lstkey.Equals("user")) {
                AppendUserListView(e.Datadt,true);
            }
            else if (lstkey.Equals("client"))
            {
                AppendClientListView(e.Datadt,true);
            }
        }
        //输出调试信息
        private void PrintReceiveBuffer(object sender, PrintReceiveDataEventArgs e)
        {
            AppendLog("#########################"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), true);
            List<string> lst=e.PrintLst;
            if (lst != null && lst.Count > 0)
            {
                foreach (string str in lst) {
                    AppendLog(str, true);
                }                
            }
        }
        private void AppendLog(string text, bool async)
        {
            if (async)
            {
                BeginInvoke(new MethodInvoker(delegate()
                {
                    infoMgsText.AppendText(text + "\n");
                }));
            }
            else
            {
                infoMgsText.AppendText(text + "\n");
            }
        }
        /// <summary>
        /// 向用户的ListView添加数据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="async">是否跨线程</param>
        private void AppendUserListView(DataTable dt, bool async)
        {
            if (async)
            {
                BeginInvoke(new MethodInvoker(delegate()
                {
                    ListViewItem lstItem;
                    int rows = 1;
                    foreach (DataRow row in dt.Rows)
                    {
                        lstItem = new ListViewItem();
                        lstItem.SubItems[0].Text = rows + "";
                        lstItem.SubItems.Add(row["usrName"].ToString().Trim());
                        lstItem.SubItems.Add(row["usrPWD"].ToString().Trim());
                        lstItem.SubItems.Add(row["Permission"].ToString().Trim());
                        lstItem.SubItems.Add(row["groupName"].ToString().Trim());
                        lstItem.SubItems.Add(row["reMark"].ToString().Trim());
                        lstUserList.Items.Add(lstItem);
                        rows++;
                    }
                }));
            }
            else
            {
                ListViewItem lstItem;
                int rows = 1;
                foreach (DataRow row in dt.Rows)
                {
                    lstItem = new ListViewItem();
                    lstItem.SubItems[0].Text = rows + "";
                    lstItem.SubItems.Add(row["usrName"].ToString().Trim());
                    lstItem.SubItems.Add(row["usrPWD"].ToString().Trim());
                    lstItem.SubItems.Add(row["Permission"].ToString().Trim());
                    lstItem.SubItems.Add(row["groupName"].ToString().Trim());
                    lstItem.SubItems.Add(row["reMark"].ToString().Trim());
                    lstUserList.Items.Add(lstItem);
                    rows++;
                }
            }
        }
        /// <summary>
        /// 向终端的ListView添加数据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="async">是否跨线程</param>
        private void AppendClientListView(DataTable dt, bool async)
        {
            if (async)
            {
                BeginInvoke(new MethodInvoker(delegate()
                {
                    ListViewItem lstItem;
                    int rowindex = 1;
                    foreach (DataRow row in dt.Rows)
                    {
                        lstItem = new ListViewItem();
                        lstItem.SubItems[0].Text = rowindex + "";
                        lstItem.SubItems.Add(row["cId"].ToString().Trim());
                        lstItem.SubItems.Add(row["cIp"].ToString().Trim());
                        lstItem.SubItems.Add(row["cPort"].ToString().Trim());
                        lstItem.SubItems.Add(row["cEndRecTime"].ToString().Trim());
                        lstClientView.Items.Add(lstItem);
                        rowindex++;
                    }
                }));
            }
            else
            {
                ListViewItem lstItem;
                int rowindex = 1;
                foreach (DataRow row in dt.Rows)
                {
                    lstItem = new ListViewItem();
                    lstItem.SubItems[0].Text = rowindex + "";
                    lstItem.SubItems.Add(row["cId"].ToString().Trim());
                    lstItem.SubItems.Add(row["cIp"].ToString().Trim());
                    lstItem.SubItems.Add(row["cPort"].ToString().Trim());
                    lstItem.SubItems.Add(row["cEndRecTime"].ToString().Trim());
                    lstClientView.Items.Add(lstItem);
                    rowindex++;
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string zhStr = "测试组1";
            byte[] bb = System.Text.Encoding.Unicode.GetBytes(zhStr);
            byte[] crc = CRCUtility.CalculateCRC(ref bb,bb.Length);

            AppendLog(DataUtility.ZhcnToHex(zhStr),false);
            AppendLog(DataUtility.ByteArrayToHexString(crc,2), false);
        }
    }
}
